package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.dto.SundayAddressDto;
import org.itboys.mobile.dto.order.SundayOrderDto;
import org.itboys.mobile.entity.mysql.order.SundayOrder;
import org.itboys.mobile.service.mongo.front.SundayFrontAddressService;
import org.itboys.mobile.service.mysql.front.SundayFrontOrderService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.MobileSignUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zhangyang
 * 时间：2017年12月18日
 * 描述：圣代_订单_controller_mobile
 */
@Controller
@RequestMapping("/sunday/mobile/order")
public class SundayMobileOrderController extends BaseController {
    @Autowired
    private SundayFrontOrderService orderService;

    /**
     * 创建订单
     * @param request
     * @param response
     * @param cartIds
     * @param isUseAiGou
     * @param isUseBalance
     * @param teamIsJoin
     * @param teamGroupId
     * @param idCard
     * @param realName
     * @param remark
     * @param addressId
     * @param nonce
     * @param sign
     */
    @RequestMapping(value="/create", method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】订单")
    public void create(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required = true, name = "cartIds", value = "购物车ID集合(非商品ID)【参与签名】。如：cardIds=1,2,3。【参与签名】") @RequestParam(value = "cartIds", required = true) List<Long> cartIds,
            @ApiParam(required = false, name = "isUseAiGou", value = "是否使用爱购币【shop==0，自营才能使用】。0否默认，1是。") @RequestParam(value="isUseAiGou",required=false) Integer isUseAiGou,
            @ApiParam(required = false, name = "isUseBalance", value = "是否使用余额【shop==0，自营才能使用】。0否默认，1是。") @RequestParam(value="isUseBalance",required=false) Integer isUseBalance,
            @ApiParam(required = false, name = "isUseConch", value = "是否使用贝壳【shop==0，自营才能使用】。0否默认，1是。type==6或type==10隐藏") @RequestParam(value="isUseConch",required=false) Integer isUseConch,
            @ApiParam(required = false, name = "teamIsJoin", value = "[拼团专用]是否参与拼团。0单独购买，1参与别人的，2自己开团") @RequestParam(value="teamIsJoin",required=false) Integer teamIsJoin,
            @ApiParam(required = false, name = "teamGroupId", value = "[拼团专用]要拼团的组ID。和[是否参与拼团==1]搭配使用。") @RequestParam(value="teamGroupId",required=false) Long teamGroupId,

            @ApiParam(required = false, name = "idCard", value = "[海淘专用]身份证号。2018年1月28日取消参数") @RequestParam(value="idCard",required=false) String idCard,
            @ApiParam(required = false, name = "realName", value = "[海淘专用]真实姓名。2018年1月28日取消参数") @RequestParam(value="realName",required=false) String realName,
            @ApiParam(required = false, name = "remark", value = "订单备注。") @RequestParam(value="remark",required=false) String remark,
            @ApiParam(required = true, name = "addressId", value = "收货地址ID") @RequestParam(value="addressId",required=true) Long addressId,
            @ApiParam(required = false, name = "sendType", value = "配送方式。至针对自营。1，门店配送（默认），2自提") @RequestParam(value="sendType",required=false) Integer sendType,
            @ApiParam(required = true, name = "nonce", value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(required = true, name = "sign", value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try{
            //2018年1月17日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();

            StringBuilder cartIdsStr=new StringBuilder();
            for(Long cartId:cartIds){
                cartIdsStr.append(cartId+",");
            }
            param.put("cartIds",cartIdsStr.substring(0,cartIdsStr.length()-1).toString());
            param.put("addressId",addressId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            Map<String,Object> result=orderService.createOrder( memberId, cartIds,
                    isUseAiGou, isUseBalance,isUseConch,
                    teamIsJoin, teamGroupId,
                    idCard, realName,
                    remark,
                    addressId,sendType);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/order/create----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    @RequestMapping(value="/getOrders",method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】分页获取订单。")
    public void getOrders(HttpServletRequest request,
                       HttpServletResponse response,
                        @ApiParam(required = false,value = "订单编号。查询参数")@RequestParam(value = "orderNo", required = false) String orderNo,
                        @ApiParam(required = true, name = "status", value = "订单状态只支持单状态。" +
                        "全部:999，1，待付款，2待配送，3配送中，4待评价，5已评价，售后（全部:999，6待退款， 7已退款，8待退货，9已退货）,10已取消,11待拼团") @RequestParam(value="status",required=true) Integer status,
                        @ApiParam(required = true, name = "flag", value = "订单前端类型，1全部订单（不含售后，试用），2我的试用（只有试用订单）3，我的售后（只含售后订单）") @RequestParam(value="flag",required=true) Integer flag,@ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                        @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                        @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
                        @ApiParam(required = false, name = "order", value = "排序参数。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
                        @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2018年1月17日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();

            param.put("nonce", nonce);
            param.put("status",status);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayOrderDto> result=orderService.getOrders(request,memberId,status,flag);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/order/select----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    @RequestMapping(value="/getDetail",method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】查看订单详情。")
    public void getDetail(HttpServletRequest request,
                        HttpServletResponse response,
                        @ApiParam(required = true, name = "orderId", value = "订单Id。【参与签名】") @RequestParam(value = "orderId", required = true)Long orderId,
                        @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2018年1月17日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();

            param.put("nonce", nonce);
            param.put("orderId",orderId);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            SundayOrderDto result=orderService.getDetail(orderId,memberId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/order/getDetail----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/cancel",method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】取消订单。待付款订单才能取消,订单状态为等于1。")
    public void cancel(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "orderId", value = "订单ID【参与签名】") @RequestParam(value = "orderId", required = true) Long orderId,
                       @ApiParam(value = "随机数【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
           /* if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.cancelOrder(orderId,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/order/cancel----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/confirmReceive",method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】确认收货。配送中订单才能确认收货,订单状态为等于3。")
    public void confirmReceive(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "orderId", value = "订单ID【参与签名】") @RequestParam(value = "orderId", required = true) Long orderId,
                       @ApiParam(value = "随机数【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
           /* if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.confirmReceive(orderId,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/order/confirmReceive----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/comment",method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】评论订单，每个商品最大传入三张图片，没有图片的评论，用noImage字符串，固定images集合大小。")
    public void comment(HttpServletRequest request,
                               HttpServletResponse response,
                                @ApiParam(required = true, name = "orderId", value = "订单ID【参与签名】") @RequestParam(value = "orderId", required = true)Long orderId,
                                @ApiParam(required = true, name = "productIds", value = "商品ID集合(productIds,contents,scores大小，顺序对应)。例如：productIds=1,2,3") @RequestParam(value = "productIds", required = true) List<Long> productIds,
                                @ApiParam(required = true, name = "contents", value = "评论内容集合，默认值：系统默认好评。(productIds,contents,scores大小，顺序对应)。例如：contents=1,2,3") @RequestParam(value = "contents", required = true) List<String> contents,
                                @ApiParam(required = true, name = "scores", value = "评分(0-5)集合。默认值：5。（productIds,contents,scores大小，顺序对应）。例如：scores=1,2,3") @RequestParam(value = "scores", required = true)List<Integer> scores,
                                @ApiParam(required = true, name = "images", value = "图片集合；，固定大小=productIds集合大小*3。每个商品限制最大传入三张，没有图片的使用noImage字符传固定值，在集合中占位") @RequestParam(value = "images", required = true)List<String> images,
                                @ApiParam(value = "随机数【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                                @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
           /* if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.commentOrder(orderId,productIds, contents,scores,images,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/order/comment----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    @RequestMapping(value="/getOrder",method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】获取单个订单")
    public void getOrder(HttpServletRequest request,
                        HttpServletResponse response,
                        @ApiParam(required = true, name = "orderId", value = "订单ID【参与签名】") @RequestParam(value = "orderId", required = true)Long orderId,
                        @ApiParam(value = "随机数【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
           /* if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/
            Long memberId = AccountIdHoldUtils.getMemberId();
            SundayOrderDto orderDto = orderService.getDetail(orderId,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/order/getOrder----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    @RequestMapping(value="/late",method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【移动端】保存售后")
    public void late(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required = true, name = "orderId", value = "订单ID【参与签名】") @RequestParam(value = "orderId", required = true) Long orderId,
            @ApiParam(required = true, name = "type", value = "类型:6待退款(待发货的状态可以退款)，8待退货(待收货的状态可以退货)【参与签名】") @RequestParam(value = "type", required = true) Integer type,
            @ApiParam(required = false, name = "afterReason", value = "申请售后原因") @RequestParam(value = "afterReason", required = false) String afterReason,
            @ApiParam(required = false, name = "afterSendCompany", value = "快递公司(申请退货时必填)") @RequestParam(value = "afterSendCompany", required = false) String afterSendCompany,
            @ApiParam(required = false, name = "afterSendCode", value = "运单编号(申请退货时必填)") @RequestParam(value = "afterSendCode", required = false) String afterSendCode,
            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);
            param.put("type",type);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
           /* if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.afterSale(orderId,memberId,type,afterReason,afterSendCompany,afterSendCode);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/order/late----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/logistics",method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】查看物流信息。h5页面直接到此页面")
    public String logistics(
            HttpServletRequest request,
            HttpServletResponse response,
            Model model,
            @ApiParam(required = true, name = "orderId", value = "订单Id。") @RequestParam(value = "orderId", required = true)Long orderId
           // @ApiParam(required = false, name = "callback", value = "返回地址。") @RequestParam(value = "callback", required = false)String callback
            ){
        try{
            // AccountIdHoldUtils.getSessionMember(request);
            Map<String,Object> result=orderService.logistics(orderId);
            model.addAttribute("result",result);
            //model.addAttribute("callback",);
            return "/aigou/mobile/order/logistics";
        }catch (Exception e){
            logger.error("/sunday/weixin/order/logistics----e="+e.getMessage());
            e.printStackTrace();
            return "/aigou/weixin/error";
        }
    }
}
